package models;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aton.config.CacheType;
import com.aton.db.SessionFactory;
import com.aton.util.MixHelper;

import enums.WdOrderTaskStatus;
import mobile.vo.Result;
import models.SellerPledgeRecord.PledgeAction;
import models.mappers.SellerPledgeRecordMapper;
import models.mappers.UserIngotRecordMapper;
import models.mappers.WdOrderTaskMapper;
import models.mappers.WdTaskMapper;
import play.cache.Cache;
import vos.Page;
import vos.WdOrderTaskSearchVo;

/**
 * 微代任务，订单子任务
 * @author zhiyuan
 * @version v1.0
 * @since 2017年3月31日 上午9:48:38
 */
public class WdOrderTask {
	
	private static final Logger log = LoggerFactory.getLogger(WdOrderTask.class);
	
	public Long id;
	public Long taskId;
	public String taskIdStr;
	public Long shareId;
	public Long buyerId;
	public String orderNo;
	public WdOrderTaskStatus status;
	public String statusTxt;
	public Date createTime;
	public Date modifyTime;
	public String remark;
	public Long cashback;
	
	public String itemPic;
	public String itemTitle;
	
	public void values(){
		this.taskIdStr = String.valueOf(this.taskId);
		if(this.status!=null){
			this.statusTxt = this.status.title;
		}
	}
	
	
	/**
	 * 统计待审核的任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月4日
	 * @param sellerId
	 * @return
	 */
	public static Integer countWaitCheckTask(Long sellerId){
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdOrderTaskMapper mapper = sqlSession.getMapper(WdOrderTaskMapper.class);
			return mapper.countWaitCheckTask(sellerId);
		}finally{
			sqlSession.close();
		}
	}
	
	/**
	 * 查询待审核的订单任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月6日
	 * @param vo
	 * @return
	 */
	public static Page<WdOrderTask> listWaitCheckOrderTask(WdOrderTaskSearchVo vo) {
		vo.status = WdOrderTaskStatus.WAIT_CHECK;
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdOrderTaskMapper mapper = sqlSession.getMapper(WdOrderTaskMapper.class);
			int count = mapper.countTask(vo);
			if(count==0){
				return Page.newInstance(vo.pageNo, vo.pageSize, count);
			}
			Page<WdOrderTask> p = Page.newInstance(vo.pageNo, vo.pageSize, count);
			p.items = mapper.listTask(vo);
			for(WdOrderTask t : p.items){
				t.values();
			}
			return p;
		}finally{
			sqlSession.close();
		}
	}

	/**
	 * 审核订单任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月6日
	 * @param id2
	 * @param result
	 * @param id3
	 */
	public static void checkOrderTask(Long id, Boolean result, long sellerId) {
		SqlSession sqlSession = SessionFactory.getSqlSessionWithoutAutoCommit();
		try{
			WdOrderTaskMapper mapper = sqlSession.getMapper(WdOrderTaskMapper.class);
			WdTaskMapper wdTaskMapper = sqlSession.getMapper(WdTaskMapper.class);
			WdOrderTask wdOrderTask = mapper.getWaitCheckTask(id, sellerId);
			
			if(wdOrderTask==null){
				log.error("未找到审核的任务[{}]", id);
				return ;
			}
			
			if(!result){
				mapper.checkOrder(WdOrderTaskStatus.DISALLOWED, id);
				sqlSession.commit();
				return ;
			}
			
			//统计已完成的订单任务数量
			WdTask wdTask = wdTaskMapper.findById(wdOrderTask.taskId);
			
			if(wdTask.sellOrderCount>=wdTask.totalOrderCount){
				long sellerPledge = User.findByIdWichCache(wdTask.sellerId).pledge;
				if(sellerPledge<wdTask.cashback){
					sqlSession.rollback();
					throw new RuntimeException("押金不足，请充值");
				}
				SellerPledgeRecordMapper sellerPledgeRecordMapper = sqlSession.getMapper(SellerPledgeRecordMapper.class);
				SellerPledgeRecord lastPledgeRecord = sellerPledgeRecordMapper.selectLastRecord(wdTask.sellerId);
				SellerPledgeRecord record = SellerPledgeRecord.newInstance(wdTask.sellerId, lastPledgeRecord);
				String memo = MixHelper.format("买手完成微代订单任务{}-{}-{}，扣除押金", wdOrderTask.taskId, wdOrderTask.shareId, wdOrderTask.id);
				record.createTime(new Date()).memo(memo).action(PledgeAction.DEDUCT_SYS_REFUND, wdTask.cashback);
				sellerPledgeRecordMapper.insert(record);
			}
			
			mapper.checkOrder(WdOrderTaskStatus.REFUNDED, id);
			
			log.info("买手{}完成微代订单任务{}-{}-{}，更新佣金", wdOrderTask.buyerId, wdOrderTask.taskId, wdOrderTask.shareId, wdOrderTask.id);
			WdTask wt = wdTaskMapper.findById(wdOrderTask.taskId);
			UserIngotRecordMapper userIngotRecordMapper = sqlSession.getMapper(UserIngotRecordMapper.class);
			UserIngotRecord lastRecode = userIngotRecordMapper.selectLastRecord(wdOrderTask.buyerId);
			
			UserIngotRecord recode = UserIngotRecord.newInstance(wdOrderTask.buyerId, lastRecode);
			String memo = MixHelper.format("微代订单任务编号{}-{}-{}订单任务已完成,获取佣金", wdOrderTask.taskId, wdOrderTask.shareId, wdOrderTask.id);
			Long commission = new BigDecimal(wt.cashback * 0.9).longValue();
			recode.plus(commission).memo(memo).isReward(true).taskId(wdOrderTask.taskId).createTime(new Date());
			userIngotRecordMapper.insert(recode);
			
			//更新任务数量
			WdTask updateWdTask = new WdTask();
			updateWdTask.id = wdTask.id;
			updateWdTask.sellOrderCount = wdTask.sellOrderCount + 1;
			
			wdTaskMapper.update(updateWdTask);
			
			sqlSession.commit();
	
			Cache.safeDelete(CacheType.USER_INFO.getKey(wdTask.sellerId));
			
			User.findByIdWichCache(wdOrderTask.buyerId).ingot(recode.balance).updateCache();
			
		}catch(Exception ex){
			log.error(ex.getMessage());
			sqlSession.rollback();
			throw new RuntimeException("审核失败...");
		}finally{
			sqlSession.close();
		}
	}
	
	/**
	 * 查询待审核的订单任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月6日
	 * @param vo
	 * @return
	 */
	public static Page<WdOrderTask> listOrderTask(WdOrderTaskSearchVo vo) {
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdOrderTaskMapper mapper = sqlSession.getMapper(WdOrderTaskMapper.class);
			int count = mapper.countTask(vo);
			if(count==0){
				return Page.newInstance(vo.pageNo, vo.pageSize, count);
			}
			Page<WdOrderTask> p = Page.newInstance(vo.pageNo, vo.pageSize, count);
			p.items = mapper.listTask(vo);
			for(WdOrderTask t : p.items){
				t.values();
			}
			return p;
		}finally{
			sqlSession.close();
		}
	}

	/**
	 * 删除订单任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月11日
	 * @param orderId
	 * @return
	 */
	public static Result delOrder(Long orderId, Long buyerId) {
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdOrderTaskMapper mapper = sqlSession.getMapper(WdOrderTaskMapper.class);
			Integer delCount = mapper.delOrder(orderId, buyerId);
			if(delCount==0){
				return Result.errorWithMsg("未找到要删除的数据");
			}
			return Result.optSuccess();
		}finally{
			sqlSession.close();
		}
	}
	
	/**
	 * 更新订单任务
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月11日
	 * @param orderId
	 * @param orderNo
	 * @param buyerId
	 * @return
	 */
	public static Result updateOrder(Long orderId, String orderNo, Long buyerId) {
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdOrderTaskMapper mapper = sqlSession.getMapper(WdOrderTaskMapper.class);
			
			Integer orderCount = mapper.countByOrderNo(orderNo);
			
			if(orderCount>0){
				return Result.errorWithMsg("此订单号在系统中已存在，请检查后重试");
			}
			
			Integer updateCount = mapper.updateOrder(orderId, orderNo, buyerId);
			if(updateCount==0){
				return Result.errorWithMsg("未找到需要修改的任务");
			}
			return Result.optSuccess();
		}finally{
			sqlSession.close();
		}
	}

	/**
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年4月15日
	 * @param taskId2
	 * @param buyerId
	 * @return
	 */
	public static List<WdOrderTask> listWdOrderByShareId(Long shareId, long buyerId) {
		SqlSession sqlSession = SessionFactory.getSqlSession();
		try{
			WdOrderTaskMapper mapper = sqlSession.getMapper(WdOrderTaskMapper.class);
			List<WdOrderTask> list = mapper.listWdOrderByShareId(shareId, buyerId);
			for(WdOrderTask obj : list){
				obj.values();
			}
			return list;
		}finally{
			sqlSession.close();
		}
	}
	
}
